package com.zcxk.dao.mapper;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
import io.vertx.core.json.JsonObject;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;

import javax.sql.DataSource;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author wangping
 * @date 2023-07-28 17:47
 */
public class SqlSession {

  private static SqlSessionFactory sqlSessionFactory = initSqlSessionFactory();

  // todo 连接池优化
  public static org.apache.ibatis.session.SqlSession getSession() {

    return sqlSessionFactory.openSession(true);
  }


  public static SqlSessionFactory initSqlSessionFactory() {
    DataSource dataSource = dataSource();
    TransactionFactory transactionFactory = new JdbcTransactionFactory();
    Environment environment = new Environment("zcxk_web", transactionFactory, dataSource);
    MybatisConfiguration configuration = new MybatisConfiguration(environment);
    configuration.addMapper(UserMapper.class);
    configuration.setLogImpl(StdOutImpl.class);
    return new MybatisSqlSessionFactoryBuilder().build(configuration);
  }

  public static DataSource dataSource() {
    try {
      // 使用类加载器读取 JSON 配置文件
      InputStream inputStream = SqlSession.class.getClassLoader().getResourceAsStream("config.json");
      if (inputStream == null) {
        throw new RuntimeException("Config file not found");
      }

      // 读取输入流并转为字符串
      String jsonString = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
      JsonObject config = new JsonObject(jsonString);

      // 从 JSON 对象中提取 JdbcPool 配置
      JsonObject jdbcConfig = config.getJsonObject("JdbcPool");

      // 创建并配置 DataSource
      SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
      dataSource.setDriverClass(com.mysql.cj.jdbc.Driver.class);
      dataSource.setUrl("jdbc:mysql://" + jdbcConfig.getString("host") + ":" + jdbcConfig.getInteger("port") + "/" + jdbcConfig.getString("database"));
      dataSource.setUsername(jdbcConfig.getString("user"));
      dataSource.setPassword(jdbcConfig.getString("password"));

      return dataSource;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}
